package com.cwd.arm.inter.conf;

import com.cwd.arm.application.service.read.UserReadServiceImpl;
import com.cwd.arm.common.enums.ErrorEnum;
import com.cwd.arm.common.encoder.ArmPasswordEncoder;
import com.cwd.arm.inter.conf.AuthHandler.FailHandler;
import com.cwd.arm.inter.conf.AuthHandler.SuccessHandler;
import com.cwd.arm.inter.vo.ResponseVo;
import com.cwd.arm.inter.vo.user.UserVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.PrintWriter;

/**
 * Created by yan on 21-11-18.
 */
@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserReadServiceImpl UserReadServiceImpl;

    @Bean
    PasswordEncoder passwordEncoder() {
        return ArmPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(UserReadServiceImpl);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // TODO: 21-11-20 改成正确的
//        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**","/webjars/**","/public/**","/static/**","/templates/**","/doc.html","/swagger-resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        http.authorizeRequests().antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/v2/**", "/api/**", "/doc.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")
                .successHandler(new SuccessHandler())
                .failureHandler(new FailHandler())
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((req, resp, authentication) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(ResponseVo.<String>BUILDER().success()));
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .csrf().disable().exceptionHandling()
                .authenticationEntryPoint((req, resp, authException) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            PrintWriter out = resp.getWriter();
                            out.write(new ObjectMapper().writeValueAsString(ResponseVo.<UserVo>BUILDER().ERROR(ErrorEnum.AUTH_ERROR, "请登录")));
                            out.flush();
                            out.close();
                        }
                );
    }
}
